package com.ruoyi.web.controller.netty.stickyPackage;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class StickPackageClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private AtomicInteger counter = new AtomicInteger(0);

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        log.info("接收到的请求数量为：" + counter.incrementAndGet());
    }

    //事件被触发后所执行的动作
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        //定义请求内容
        String request = "abcdefghijklmnopqrstuvwxyz" + System.getProperty("line.separator");
//        String request = "abcdefghijklmnopqrstuvwxyz" + "@_";
        final ByteBufAllocator byteBufAllocator = ctx.alloc();
        ByteBuf msg = null;
        //给服务器发送10个报文
        for(int i=0;i<10;i++){
            msg = byteBufAllocator.buffer(request.length());
            msg.writeBytes(request.getBytes());
            ctx.writeAndFlush(msg);
        }
    }
}
